package com.houweishi.module.fileUploadRecord.service.impl;

import com.houweishi.common.constant.Constants;
import com.houweishi.common.constant.HttpStatus;
import com.houweishi.common.core.domain.AjaxResult;
import com.houweishi.common.core.domain.model.LoginUser;
import com.houweishi.common.exception.base.BaseException;
import com.houweishi.common.utils.DateUtils;
import com.houweishi.common.utils.SecurityUtils;
import com.houweishi.file.utils.FileUtils;
import com.houweishi.module.fileUploadRecord.domain.BizFileUploadRecord;
import com.houweishi.module.fileUploadRecord.mapper.BizFileUploadRecordMapper;
import com.houweishi.module.fileUploadRecord.service.IBizFileUploadRecordService;
import com.houweishi.system.service.ISysDeptService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Objects;

import static com.houweishi.common.utils.PageUtils.startPage;

/**
 * 文件上传记录Service业务层处理
 * 
 * @author houweishi
 * @date 2023-03-24
 */
@Service
public class BizFileUploadRecordServiceImpl implements IBizFileUploadRecordService 
{
    private static final Logger LOGGER = LoggerFactory.getLogger(BizFileUploadRecordServiceImpl.class);
    @Resource
    private BizFileUploadRecordMapper bizFileUploadRecordMapper;

    @Autowired
    private FileUtils fileUtils;

    /**
     * 部门
     */
    @Autowired
    private ISysDeptService iSysDeptService;

    /**
     * 查询文件上传记录
     * 
     * @param id 文件上传记录主键
     * @return 文件上传记录
     */
    @Override
    public BizFileUploadRecord selectBizFileUploadRecordById(Long id)
    {
        return bizFileUploadRecordMapper.selectBizFileUploadRecordById(id);
    }

    /**
     * 查询文件上传记录列表
     * 
     * @param bizFileUploadRecord 文件上传记录
     * @return 文件上传记录
     */
    @Override
    public List<BizFileUploadRecord> selectBizFileUploadRecordList(BizFileUploadRecord bizFileUploadRecord)
    {
        //查询公司文件数据权限处理：分公司只能看分公司的，总公司可以看所有数据
        if ("company".equals(bizFileUploadRecord.getTag())){
            //获取当前人部门id
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (Objects.isNull(loginUser)){
                throw new BaseException("请先登录");
            }
            String company = iSysDeptService.findCompanyByDeptId(loginUser.getDeptId());
            bizFileUploadRecord.setCompany(company);
            if ("猴卫士".equals(company)){
                bizFileUploadRecord.setCompany(null);
            }
            bizFileUploadRecord.setDeptId(null);
        }
        startPage();
        return bizFileUploadRecordMapper.selectBizFileUploadRecordList(bizFileUploadRecord);
    }

    /**
     * 新增文件上传记录
     * 
     * @param bizFileUploadRecord 文件上传记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertBizFileUploadRecord(BizFileUploadRecord bizFileUploadRecord)
    {
        //获取当前人
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser==null){
            return new AjaxResult(HttpStatus.UNAUTHORIZED,"请先登录");
        }
        //获取当前人部门
        String company = iSysDeptService.findCompanyByDeptId(loginUser.getDeptId());
        bizFileUploadRecord.setCompany(company);
        bizFileUploadRecord.setState(Constants.DATA_VALID_STATE);
        bizFileUploadRecord.setUserId(loginUser.getUserId());
        bizFileUploadRecord.setUserName(loginUser.getUsername());
        bizFileUploadRecord.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
        bizFileUploadRecord.setUpdateBy(loginUser.getUsername());
        bizFileUploadRecord.setCreateBy(loginUser.getUsername());
        bizFileUploadRecord.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
        bizFileUploadRecordMapper.insertBizFileUploadRecord(bizFileUploadRecord);
        return AjaxResult.success();
    }

    /**
     * 修改文件上传记录
     * @param bizFileUploadRecord
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateBizFileUploadRecord(BizFileUploadRecord bizFileUploadRecord)
    {
        //获取当前人
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser==null){
            return new AjaxResult(HttpStatus.UNAUTHORIZED,"请先登录");
        }
        bizFileUploadRecord.setState(Constants.DATA_VALID_STATE);
        bizFileUploadRecord.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
        bizFileUploadRecord.setUpdateBy(loginUser.getUsername());
        bizFileUploadRecordMapper.updateBizFileUploadRecord(bizFileUploadRecord);
        return AjaxResult.success();
    }

    /**
     * 批量删除文件上传记录
     * 
     * @param ids 需要删除的文件上传记录主键
     * @return 结果
     */
    @Override
    public int deleteBizFileUploadRecordByIds(Long[] ids)
    {
        return bizFileUploadRecordMapper.deleteBizFileUploadRecordByIds(ids);
    }

    /**
     * 删除文件上传记录信息
     * 
     * @param id 文件上传记录主键
     * @return 结果
     */
    @Override
    public int deleteBizFileUploadRecordById(Long id)
    {
        return bizFileUploadRecordMapper.deleteBizFileUploadRecordById(id);
    }

    /**
     * 文件下载
     * @param bizFileUploadRecord
     * @param response
     * @return
     */
    @Override
    public AjaxResult downloadFile(BizFileUploadRecord bizFileUploadRecord, HttpServletResponse response) {
        try {
            fileUtils.download(bizFileUploadRecord.getServerFileName(),bizFileUploadRecord.getFilePath(),response);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("文件下载失败",e);
            throw new RuntimeException(e);
        }
        return AjaxResult.success();
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    @Override
    public AjaxResult uploadFile(MultipartFile file) {
        return AjaxResult.success(fileUtils.upload(file));
    }

}
